* ----------------------------------------------------------------
* marginal effects of close elections on cross-cutting exposure and network isolation
* ----------------------------------------------------------------
set more off 

use "./data/processed/CE_cleaned_reg.dta",clear 

* two-way fixed effects logit cluster error models 
gen DV_name = ""
gen model_year = .
gen coef0 = . 
gen se0 = . 
gen lci0 = . 
gen uci0 = . 
gen coef1 = . 
gen se1 = . 
gen lci1 = . 
gen uci1 = . 

cap: program drop run_model2_size
program run_model2_size 
args DV year n
	di `n'
	if "`DV'" == "n_size4" {
		if `year' == 0 {
			poisson `DV' c.r_age r_female c.r_educ i.r_race r_married r_working   i.year i.state_code i.close_election [pw=wt] if one == 1, cluster(state_code)
		} 
		else {
			poisson `DV' c.r_age r_female c.r_educ i.r_race r_married r_working   i.close_election [pw=wt]  if year == `year' & one == 1, cluster(state_code) 
		}		
	}
	else {
		if `year' == 0 {
			logit `DV' c.r_age r_female c.r_educ i.r_race r_married r_working   i.year i.state_code i.close_election [pw=wt] if one == 1, cluster(state_code)
		} 
		else {
			logit `DV' c.r_age r_female c.r_educ i.r_race r_married r_working   i.close_election [pw=wt]  if year == `year' & one == 1, cluster(state_code) 
		}		
	}
	margins close_election
	matrix margin_table = r(table)
	replace DV_name = "`DV'" in `n'
	replace model_year = `year' in `n'
	replace coef0 = margin_table[1,1] in `n'
	replace se0   = margin_table[2,1] in `n'
	replace lci0  = margin_table[5,1] in `n'
	replace uci0  = margin_table[6,1] in `n'

	replace coef1 = margin_table[1,2] in `n'
	replace se1   = margin_table[2,2] in `n'
	replace lci1  = margin_table[5,2] in `n'
	replace uci1  = margin_table[6,2] in `n'

end 

* ------------------------------------------------------------
* run models 
* ------------------------------------------------------------
local j = 1
foreach X of var  isolation pol_one_diff {
	local n1 = 1+(`j'-1) * 5 
	run_model2_size `X' 0 `n1'
	local n1 = `n1'+1
	run_model2_size `X' 1992 `n1'
	local n1 = `n1'+1
	run_model2_size `X' 2000 `n1'
	local n1 = `n1'+1
	run_model2_size `X' 2008 `n1'
	local n1 = `n1'+1
	run_model2_size `X' 2016 `n1'
	local j = `j' + 1 
}

outsheet DV_name-uci1 using ./output/margin_effect_yearly.csv, comma replace, if DV_name != ""


